package com.googlecode.util.codecheck;

/**
 * Created by IntelliJ IDEA.
 * User: Howard
 * Date: 2009-4-10
 * Time: 18:08:02
 * To change this template use File | Settings | File Templates.
 */

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CodeFilterForSSecurity extends HttpServlet implements Filter {
    /**
     * 判断用户输入的验证码是否正确
     */
    private static final long serialVersionUID = -5838154525730151323L;

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String code = request.getParameter("j_code");
//        Cookie[] cookie = request.getCookies();
//        String codes = "";
//        for (int i = 0; cookie != null && i < cookie.length; i++) {
//            if ("codes".equals(cookie[i].getName())) {
//                codes = cookie[i].getValue();
//            }
//        }
        String SourceCode = (String)request.getSession().getAttribute("randcode");
        if (!"".equals(SourceCode) && SourceCode != null) {
            if (code.equalsIgnoreCase(SourceCode)) {
                filterChain.doFilter(request, response);
            } else {
                response.sendRedirect("login?error="+java.net.URLEncoder.encode("验证码错误","utf-8"));
            }
        } else {
            response.sendRedirect("login?error="+java.net.URLEncoder.encode("验证码错误","utf-8"));
        }
    }
}
